package com.miss.spjyx.utils

import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.os.Handler
import android.os.Message
import android.util.Log
import android.view.KeyEvent
import com.uhf.scanlable.UHfData
import java.util.*

/**
 * @author wl
 * @since 2019/08/31 21:18
 */
object UHfUtils {
    private const val devport = "/dev/ttyMT1"
    private var startTime: Long = 0
    private var keyUpFalg = true
    private var isCanceled = true
    private val SCAN_INTERVAL = 5
    private val MSG_UPDATE_LISTVIEW = 0
    private val keyReceiver = object : BroadcastReceiver() {
        override fun onReceive(context: Context, intent: Intent) {
            var keyCode = intent.getIntExtra("keyCode", 0)
            // H941
            if (keyCode == 0) {
                keyCode = intent.getIntExtra("keycode", 0)
            }
            val keyDown = intent.getBooleanExtra("keydown", false)
            if (keyUpFalg && keyDown && System.currentTimeMillis() - startTime > 500) {
                keyUpFalg = false
                startTime = System.currentTimeMillis()
                if (keyCode == KeyEvent.KEYCODE_F3) {
                    doScan()
                }
                return
            } else if (keyDown) {
                startTime = System.currentTimeMillis()
            } else {
                keyUpFalg = true
            }

        }
    }

    private class MsgHandler internal constructor(instance: UHfUtils) : Handler() {
        override fun handleMessage(msg: Message) {
            if (isCanceled)
                return
            when (msg.what) {
                MSG_UPDATE_LISTVIEW -> {
                    val data = UHfData.lsTagList
                    li?.onDataChange(data)

                    if (UHfData.mIsNew) {
                        Thread(Runnable {
                            if (!SoundUtils.soundfinished)
                                SoundUtils.play(1, 0)
                        }).start()
                        UHfData.mIsNew = false
                    }
                }
                else -> {
                }
            }
        }
    }

    private lateinit var mHandler: Handler
    private var timer: Timer? = null
    private var Scanflag = false
    private var isRegister = false

    var li: onDataGotListener? = null

    private fun doScan() {
        try {
            if (timer == null) {
                UHfData.lsTagList.clear()
                UHfData.dtIndexMap.clear()
                li?.onDataChange(UHfData.lsTagList)

                mHandler.removeMessages(MSG_UPDATE_LISTVIEW)
                mHandler.sendEmptyMessage(MSG_UPDATE_LISTVIEW)

                isCanceled = false
                timer = Timer()
                timer?.schedule(object : TimerTask() {
                    override fun run() {
                        if (Scanflag)
                            return
                        Scanflag = true
                        UHfData.Inventory_6c(1, 0)
                        // UHfData.Inventory_6c_Mask((byte)0, 16, 0, UHfGetData.hexStringToBytes("E200"));
                        mHandler.removeMessages(MSG_UPDATE_LISTVIEW)
                        mHandler.sendEmptyMessage(MSG_UPDATE_LISTVIEW)
                        Scanflag = false
                    }
                }, 0, SCAN_INTERVAL.toLong())
            } else {
                isCanceled = true
                timer?.cancel()
                timer = null
            }
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }

    fun register(context: Context) {
        if (isRegister) return
        Log.d("spjyx", "register spj button listener")
        try {
            UHfData.lsTagList.clear()
            UHfData.dtIndexMap.clear()
            li?.onDataChange(UHfData.lsTagList)
        } catch (e: Exception) {
            e.printStackTrace()
        }

        val filter = IntentFilter()
        filter.addAction("android.rfid.FUN_KEY")
        context.registerReceiver(keyReceiver, filter)
    }

    fun unregister(context: Context) {
        if (!isRegister) return
        Log.d("spjyx", "unregister spj button listener")
        try {
            cancelScan()
            context.unregisterReceiver(keyReceiver)
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }

    private fun cancelScan() {
        isCanceled = true
        mHandler.removeMessages(MSG_UPDATE_LISTVIEW)
        timer?.cancel()
        timer = null
        UHfData.lsTagList.clear()
        UHfData.dtIndexMap.clear()
        li?.onDataChange(UHfData.lsTagList)
    }

    interface onDataGotListener {
        fun onDataChange(data: List<UHfData.InventoryTagMap>)
    }

    fun openUHf(): Int {
        return UHfData.UHfGetData.OpenUHf(devport, 57600)
    }

    fun init() {
        mHandler = MsgHandler(this)
    }

    fun closeUHf() {
        UHfData.UHfGetData.CloseUHf()
    }
}
